package com.cao.meet.bean;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Created by ZKTH
 * Time ： 2018/12/11.9:44
 * data ：
 */

public class XmlAnaly {
    private static Map<String, String> map;

    public static Map<String, String> execute(String paramstr) throws Exception {
        map =  new HashMap<String, String>();
        // 创建xml的Document对象
        Document document = DocumentHelper.parseText(paramstr);
        // 遍历节点的所有属性
        Element root = document.getRootElement();
        getNodes(root);
        return map;
    }

    /**
     * 从指定节点开始，递归遍历所有子节点
     *
     * @throws Exception
     */
    public static void getNodes(Element node) {

        String key = "";
        String val = "";
        // 获取当前节点的属性
        List<Attribute> listAttr = node.attributes();
        // 递归遍历当前节点所有子节点
        List<Element> listElement = node.elements();
        for (Element e : listElement) {
            String attrValue = "";
            if(e.attributes().size() > 0){
                Attribute attr = (Attribute) e.attributes().get(0);
                attrValue = attr.getValue();
            }

            if (e.getTextTrim() != "" && e.getTextTrim() != null) {
                if (attrValue != "" && attrValue != null) {
                    key = e.getName()+"_"+attrValue;
                } else {
                    key = e.getName();
                }
                val = e.getTextTrim();
            }
            map.put(key, val);
            getNodes(e);// 递归
        }
    }

    // 用于判断是否有子节点,若有就将子节点也进行拼接,若无则返回""
    public static String checkChildEle(Element element) throws DocumentException {
        String json = "";
        List<Element> list = new ArrayList<Element>();
        list = element.elements();
        if (list.size() > 0) {
            for (Element ele : list) {
                List<Attribute> listAttr = ele.attributes();
                String attrvalue = "";
                if(listAttr.size()>0){
                    attrvalue = listAttr.get(0).getValue();
                    System.out.println("12####"+attrvalue);
                }

                json += "\""+ele.getName().trim()+"_"+attrvalue + "\""+":" + "\""+ele.getText().trim() + "\""+"," + "\n"
                        + checkChildEle(ele);
            }
        }
        return json;
    }

    // 这个方法是将xml字符串转成Json
    public static String xmlChangeJson(String XML) throws DocumentException {
        if(XML.indexOf("<!DOCTYPE")>=0){
            XML = XML.replace(XML.substring(XML.indexOf("<!DOCTYPE"), XML.indexOf("dtd\">")+5), "");
        }
        Document document = DocumentHelper.parseText(XML);
        Element root = document.getRootElement();
        Iterator it = root.elementIterator();
        String json = "{";
        while (it.hasNext()) {
            Element element = (Element) it.next();
            String j = checkChildEle(element);

            if (j == "") {
                json += "\""+element.getName() .trim()+"\""+":"+ "\""+element.getText().trim() + "\""
                        + ",";
            } else {
                json += j;
            }

        }
        json = json.substring(0, json.lastIndexOf(","));
        json += "}";
        return json;
    }

    // 这个方法是将xml文件转成Json
    public static String xmlChangeJson(File XML) throws DocumentException {
        SAXReader reader = new SAXReader();
        Document document = reader.read(XML);
        Element root = document.getRootElement();
        Iterator it = root.elementIterator();
        String json = "{";
        while (it.hasNext()) {
            Element element = (Element) it.next();
            String j = checkChildEle(element);
            if (j == "") {
                json += "\""+element.getName() +"\""+":"+ "\""+element.getText().trim() + "\""
                        + ",";
            } else {
                json += j;
            }

        }
        json = json.substring(0, json.lastIndexOf(","));
        json += "}";
        return json;
    }

    public static Map<String, String> domjxml(String paramstr) throws Exception {
        map =  new HashMap<String, String>();
        try {
            // 将xml格式字符串转化为DOM对象
            org.dom4j.Document document = DocumentHelper.parseText(paramstr);
            // 获取根结点对象
            Element rootElement = document.getRootElement();
            Attribute rootattr = rootElement.attribute("Success");
            map.put("rootSuccess", rootattr.getValue());
            // 循环根节点，获取其子节点
            for (Iterator iter = rootElement.elementIterator(); iter.hasNext();) {
                Element element = (Element) iter.next(); // 获取标签对象
                // 获取该标签对象的属性
                Attribute attr = element.attribute("Success");
                if (null != attr) {
                    String attrVal = attr.getValue();
                    String attrName = attr.getName();
                    map.put("zappSuccess", attrVal);
                }
                // 循环第一层节点，获取其子节点
                for (Iterator iterInner = element.elementIterator(); iterInner
                        .hasNext();) {
                    // 获取标签对象
                    Element elementOption = (Element) iterInner.next();
                    // 获取该标签对象的名称
                    String tagName = elementOption.getName();
                    // 获取该标签对象的内容
                    String tagContent = elementOption.getTextTrim();
                    // 输出内容
                    map.put(tagName, tagContent);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }
}